package com.gitee.cashzhang27.test.boot.other.util;


import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.layout.font.FontProvider;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;

/**
 * @author cash Zhang
 * @since 2018/12/13 14:22
 */
@Slf4j
public class ITextUtils {

  private static final String PDF_SUFFIX = ".pdf";

  public static String html2pdf(String htmlSourcePath, String pdfDestPath, String fileName)
      throws IOException {
    String pdfPathName = pdfDestPath + File.separator+ fileName + PDF_SUFFIX;

    File htmlSource = new File(htmlSourcePath);
    File pdfDest = new File(pdfPathName);

    String baseFontPathName = Thread.currentThread().getContextClassLoader()
        .getResource("").getPath() + "font/";

    String os = System.getProperty("os.name");
    if (os.toLowerCase().startsWith("win")) {
      baseFontPathName = baseFontPathName.substring(1);
    }
    // pdfHTML specific code
    ConverterProperties converterProperties = new ConverterProperties();
    FontProvider fontProvider = new FontProvider();
    // 宋体
    PdfFont simsunTtcFont = PdfFontFactory.createTtcFont(baseFontPathName + "Simsun.ttc", 1,
        PdfEncodings.IDENTITY_H, false, true);
    fontProvider.addFont(simsunTtcFont.getFontProgram());

//    fontProvider.addFont(baseFontPathName + "NotoSansCJKsc-Regular.otf");
    converterProperties.setFontProvider(fontProvider);
    converterProperties.setCharset("utf-8");

    HtmlConverter
        .convertToPdf(new FileInputStream(htmlSource), new FileOutputStream(pdfDest),
            converterProperties);
    return pdfDest.getPath();
  }
}
